package com.jk.garden1.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jk.garden1.dao.*;
import com.jk.garden1.entity.SubscribeEntity;
import com.jk.garden1.entity.UserMiniEntity;
import com.jk.garden1.entity.VisitantEntity;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.xml.crypto.Data;
import java.util.*;

/**
 * 到访管理表
 */
@Service
public class VisitantService {
    @Autowired
    private VisitantDao visitantDao;
    @Autowired
    private VisitantDaos visitantDaos;
    @Autowired
    private SubscribeDao subscribeDao;
    @Autowired
    private ElasticsearchRestTemplate es;
    @Autowired
    private EsVisitantDao esVisitantDao;
    @Autowired
    private UserMinDao userMinDao;
    /**
     * 查询全部
     */
    public List<VisitantEntity> selectList(VisitantEntity visitantEntity) {
        Map map=new HashMap();
        if (visitantEntity.getVisitantname() !=null && visitantEntity.getVisitantname() !="")
            map.put("visitantname",visitantEntity.getVisitantname());
        if (visitantEntity.getIntervieweename() !=null && visitantEntity.getIntervieweename() !="")
            map.put("intervieweename",visitantEntity.getIntervieweename());
        return visitantDao.selectByMap(map);
    }
    /**
     * 新增临时到访
     */
    public void addVisitant(VisitantEntity visitantEntity) {
        visitantDao.insert(visitantEntity);
    }

    public void delAndAdd(Integer id) {

        VisitantEntity visitantEntity = visitantDao.selectById(id);
        SubscribeEntity subscribeEntity = new SubscribeEntity();
        subscribeEntity.setVisitantname(visitantEntity.getVisitantname());
        subscribeEntity.setVisitantphone(visitantEntity.getVisitantphone());
        subscribeEntity.setIntervieweename(visitantEntity.getIntervieweename());
        subscribeEntity.setIntervieweecompany(visitantEntity.getIntervieweename());
        subscribeEntity.setSubscribestatus("以签退");
        subscribeDao.insert(subscribeEntity);
        visitantDao.deleteById(id);
    }

    /**
     * 新增索引
     */
    public void create(){
        es.createIndex(VisitantEntity.class);
        QueryWrapper wp=new QueryWrapper();
        List<VisitantEntity> list = visitantDao.selectList(wp);
        list.forEach(a -> {
            esVisitantDao.save(a);
        });
    }

    /**
     * es高亮
     * @param visitantEntity
     * @return
     */
    public List<VisitantEntity> selectListes(VisitantEntity visitantEntity) {
        if (es.indexExists(VisitantEntity.class)){
            create();
        }
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //被访姓名模糊查
        if(StringUtils.hasText(visitantEntity.getIntervieweename())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("intervieweename",visitantEntity.getIntervieweename()));
        }
        //访客名称模糊查
        if(StringUtils.hasText(visitantEntity.getVisitantname())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("visitantname",visitantEntity.getVisitantname()))
                    .withHighlightFields(new HighlightBuilder.Field("visitantname").preTags("<font color='red'>").postTags("</font>"));
        }
        SearchQuery build = nativeSearchQueryBuilder.build();
        if(StringUtils.hasText(visitantEntity.getVisitantname())){
            AggregatedPage<VisitantEntity> employeeEntity = es.queryForPage(build, VisitantEntity.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    SearchHits hits = searchResponse.getHits();
                    List list = new ArrayList();
                    for (SearchHit hit : hits) {
                        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                        sourceAsMap.put("visitantname", highlightFields.get("visitantname").getFragments()[0].toString());
                        list.add(sourceAsMap);
                    }
                    return new AggregatedPageImpl<>(list);
                }
                @Override
                public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
                    return null;
                }
            });
            return employeeEntity.getContent();
        }else{
            List<VisitantEntity> list2 = es.queryForList(build, VisitantEntity.class);
            return  list2;
        }
    }

    public List<VisitantEntity> findcount(VisitantEntity visitantEntity) {
        return visitantDaos.findcount(visitantEntity);
    }
    /**
     *
     * 扫一扫添加到访
     */
    public void addVisitantList(VisitantEntity visitantEntity) {
        String visitantname = visitantEntity.getVisitantname();
        UserMiniEntity userMiniEntity=userMinDao.findUserInfo(visitantname);
        if (userMiniEntity.getIdentity().equals("员工")){
            //员工
            VisitantEntity visitantEntity1 = new VisitantEntity();
            visitantEntity1.setThroughcard(userMiniEntity.getCompanycode());
            visitantEntity1.setVisitantname(userMiniEntity.getUsername());
            visitantEntity1.setVisitantphone(userMiniEntity.getPhone());
            visitantEntity1.setSignintime(new Date().toLocaleString());
            visitantEntity1.setClassify(userMiniEntity.getIdentity());
            visitantDao.insert(visitantEntity1);
        }else {
            //访客
            VisitantEntity visitantEntity1 = new VisitantEntity();
            visitantEntity1.setThroughcard(userMiniEntity.getCompanycode());
            visitantEntity1.setVisitantname(userMiniEntity.getUsername());
            visitantEntity1.setVisitantphone(userMiniEntity.getPhone());
            visitantEntity1.setSignintime(new Date().toLocaleString());
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR_OF_DAY,12);
            visitantEntity1.setSignouttime(calendar.getTime().toLocaleString());
            visitantEntity1.setClassify(userMiniEntity.getIdentity());
            visitantDao.insert(visitantEntity1);
        }
    }

    public List<VisitantEntity> findLinShi(VisitantEntity visitantEntity) {
        return visitantDaos.findLinShi(visitantEntity);
    }
}
